<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/11/23
 * Time: 10:52
 */

namespace Api\Controller;
use Shop\Api\OrdersApi;
use Admin\Api\InternationalAlipayNotifyApi;
use Shop\Model\OrdersModel;
use Library\Api\ZjportUploadHisApi;
use Library\Model\ZjportUploadHisModel;

/**
 * 支付单上报
 * Class ZjportPayController
 * @package Api\Controller
 */
class ZjportPayController  extends  ApiController{

    /**
     * 支付宝的支付单上报
     */
    public function upload(){

        $order_code = $this->_post("order_code","","缺少订单号!");
        $haiguan = $this->_post("haiguan","","上报海关必填!");
        $result = apiCall(OrdersApi::GET_INFO,array(array('order_code'=>$order_code)));

        $this->checkApiCallResult($result,true,"订单信息获取失败!");
        $order = $result['info'];

        addLog("ZjportPay/alipay_upload",$order,$haiguan,"[result] 支付宝上报",true);
        switch($order['pay_type']){
            case OrdersModel::PAY_TYPE_ALIPAY:
                $this->alipay_upload($order,$haiguan);
                break;
            default:
                $this->apiReturnErr("不支持的支付类型!");
                break;
        }




    }

    private function alipay_upload($order,$haiguan){

        addLog("ZjportPay/alipay_upload",$order,$haiguan,"[result] 支付宝上报",true);
        //TODO: 多个时
        $out_request_no = $this->getRequestNo();
        $pay_code = $order['pay_code'];
        $amount = $order['price'];

        $result = apiCall(InternationalAlipayNotifyApi::GET_INFO,array(array('out_trade_no'=>$pay_code)));

        $this->checkApiCallResult($result,true,"订单支付信息获取失败!");

        $alipayInfo = $result['info'];

        $trade_no = $alipayInfo['trade_no'];
        $amount = $alipayInfo['total_fee'];

        $result = apiCall(OrdersApi::GET_INFO,array(array('pay_code'=>$trade_no)));

        $parameter = array(
            "service" => "alipay.acquire.customs",
            "partner" => trim($this->alipay_config['partner']),
            "_input_charset" =>'utf-8',
            "out_request_no"=>$out_request_no,
            "trade_no"=>$trade_no,
            'amount'=>$amount,
            "merchant_customs_code"=>'341905490',
            "merchant_customs_name"=>'杭州马班科技有限公司',
            'customs_place'=>$haiguan,
        );

        //建立请求
        $alipaySubmit = new \AlipaySubmit($this->alipay_config);
        $result = $alipaySubmit->buildRequestHttp($parameter,"get","");
        addLog("ZjportPay/upload",$result,$parameter,"[result] 支付宝上报",true);
        $this->addToHistory($order['order_code'],$out_request_no,$parameter,$result);

        addLog("ZjportPay/alipay_upload",$parameter,$result,"[调试]支付宝支付单上报结果",true);

        $xml  = (array)simplexml_load_string($result);

        $this->parseReturn($xml);
    }

    private function addToHistory($order_code,$serial_no,$upload_content,$result=""){
        if(empty($upload_content)){
            $upload_content = "";
        }

        if(empty($result)){
            $result = "";
        }

        if(is_array($upload_content)){
            $upload_content = json_encode($upload_content);
        }
        if(is_array($result)){
            $result = json_encode($result);
        }

        $entity = array(
            'order_code'=>$order_code,
            'upload_time'=>NOW_TIME,
            'serial_no'=>$serial_no,
            'asyn_result'=>'',
            'result'=>$result,
            'upload_content'=>$upload_content,
            'type'=>ZjportUploadHisModel::UPLOAD_PAY_TYPE,
        );

        $result = apiCall(ZjportUploadHisApi::ADD,array($entity));

    }

    private function parseReturn($xml){
//        dump($xml);
        if(strtolower($xml['is_success']) == strtolower('T')){
            //
            $response = $xml['response'];
            $alipay = $response->xpath("alipay");

//          dump($alipay[0]->result_code);

            if($alipay[0]->result_code == "FAIL"){

                $des_code = (array)$alipay[0]->detail_error_code;
                $des = (array)$alipay[0]->detail_error_des;
                $this->apiReturnErr($des_code[0].":".$des[0]);
            }else{

                $declare_no = $alipay[0]->alipay_declare_no[0];
                //TODO: 写入数据库
                $this->apiReturnSuc("处理成功!");
            }


        }else{
            $this->apiReturnErr($xml['error']);
        }
    }

    private function getRequestNo(){
        $no = date("YmdHis");
        //TODO: 纪录到数据库，
        return $no;
    }

    private  $alipay_config;

    /**
     * 初始化
     */
    public function _init(){
        parent::_init();

        $this->alipay_config = $this->getAlipayConfig();
        //引入支付官方sdk
        vendor('alipay_submit',APP_PATH.'Api/Vendor/InternationalAlipay/','.class.php');
    }

    private function getAlipayConfig(){
        //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//        $alipay_config['partner']		= C('ALIPAY_API.TEST_INTERNATIONAL_ALIPAY_PARTNER');
//
//        //安全检验码，以数字和字母组成的32位字符
//        $alipay_config['key']			=  C('ALIPAY_API.TEST_INTERNATIONAL_ALIPAY_KEY');

        //合作身份者id，以2088开头的16位纯数字
        $alipay_config['partner']		= C('ALIPAY_API.INTERNATIONAL_ALIPAY_PARTNER');

        //安全检验码，以数字和字母组成的32位字符
        $alipay_config['key']			=  C('ALIPAY_API.INTERNATIONAL_ALIPAY_KEY');


        //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

        $alipay_config['return_url'] = C('ALIPAY_API.INTERNATIONAL_ALIPAY_RETURN_URL');
        //After the payment transaction is done
        //Notification URL
        $alipay_config['notify_url'] = C('ALIPAY_API.INTERNATIONAL_ALIPAY_NOTIFY_URL');

        //签名方式 不需修改
        $alipay_config['sign_type']    = strtoupper('MD5');

        //字符编码格式 目前支持 gbk 或 utf-8
        $alipay_config['input_charset']= strtolower('utf-8');

        //ca证书路径地址，用于curl中ssl校验
        //请保证cacert.pem文件在当前文件夹目录中
//        $alipay_config['cacert']    = getcwd().'\\cacert.pem';
        $alipay_config['cacert']    = APP_PATH.'Api/Vendor/InternationalAlipay/cacert.pem';

        //访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
        $alipay_config['transport']    = 'http';

        return $alipay_config;
    }
}